package com.isoftstone.demo.global.controller;


import com.isoftstone.demo.global.entity.Demo;
import com.isoftstone.demo.global.service.DemoService;
import com.isoftstone.services.base.RespBaseController;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.*;

/**
 * Demo控制器
 *
 * @author TianGanLin
 * @version 1.0.0, 2017/11/24
 * @see com.isoftstone.demo.global.entity.Demo
 * @since Demo
 */
@RestController
@RequestMapping("/demos")
public class DemoController extends RespBaseController<DemoService> {

    /**
     * 默认排除的属性
     */
    private final String[] DEFAULT_EXCEPT = {"someSet"};

    /**
     * 注入模块ID
     *
     * @return 模块ID
     */
    @Override
    public Long getModuleId() {
        return null;
    }

    /**
     * 新增
     *
     * @param demo 数据
     */
    @PostMapping
    public String add(Demo demo) throws Exception {
        // 操作对象（用于生成日志）
        Operation operation = new Operation("log.demo.add").setMsgArgs(demo.getName());
        // 执行业务、生成日志、返回Json
        return respJson(() -> toJson(service().add(demo)), operation);
    }

    /**
     * 更新
     */
    @PutMapping
    public String update(Demo demo) throws Exception {
        // 操作对象（用于生成日志）
        Operation operation = new Operation("log.demo.update").setMsgArgs(demo.getName());
        return respSuccess(() -> service.save(demo), operation);
    }

    /**
     * 获取
     */
    @GetMapping(value = "/{id}")
    public String get(@PathVariable Integer id) throws Exception {
        return respJson(() -> {
            Demo demo = service().get(id);
            return toJson(demo);
        });
    }

    /**
     * 删除
     */
    @DeleteMapping(value = "/{id}")
    public String delete(@PathVariable Integer id) throws Exception {
        // 操作对象（用于生成日志）
        Operation operation = new Operation("log.demo.delete");
        return respSuccess(() -> {
            Demo demo = service().findOne(id);
            operation.setMsgArgs(demo.getName());
            service.delete(id);
        }, operation);
    }

    /**
     * 分页查询
     *
     * @param demo     实体类数据
     * @param pageable 分页
     */
    @RequestMapping("/paging")
    public String paging(Demo demo, @PageableDefault Pageable pageable) {
        Page<Demo> page = service().paging(demo, pageable);
        return toJsonExcept(page, Demo.class, DEFAULT_EXCEPT);
    }
    
    /**
     * 普通搜索，验证时间传参
     * @param demo
     * @return
     */
    @PostMapping("/search")
    public String search(@RequestBody Demo demo) {
        Demo demos = demo;
        return toJsonExcept(demos, Demo.class, DEFAULT_EXCEPT);
    }
}
